import React, { Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import {  WeaTop,WeaTab, WeaRightMenu, WeaAlertPage, WeaHelpfulTip } from 'ecCom';
import { Button } from 'antd';
import { CustomPageStore } from '../../stores/custompage';
import { TreeStore } from '../../stores/tree';
import CardStore from '../../stores/card';
import { listStore } from '../../stores/list';
import ReplyStore from '../../stores/reply';
// import { UrlDocker } from '../index';
import { toJS } from 'mobx';
import List from '../list';
import { InnerTabCard } from '../card';
import ReplySingle from '../reply/replySingle';
import Tree from '../tree';
import { WeaLocaleProvider } from 'ecCom';
import jQuery from "jquery";

const getLabel = WeaLocaleProvider.getLabel;

export interface CustomPageStoreProps {
    customPageStore: CustomPageStore,
    Tree: TreeStore;
    Card: CardStore;
    Search: listStore;
    reply: ReplyStore;
}

@inject('customPageStore', 'Search')
@observer
export default class CustomPage extends React.Component<CustomPageStoreProps, any> {
    componentWillUnmount() {
        const { customPageStore } = this.props;     
        customPageStore.clearStatus();
    }
    componentDidUpdate() {
        const { customPageStore, Search } = this.props;
        const { detailData } = customPageStore;
        const { countDisplayPosition, countData } = Search;
        let array = new Array();
        let i = 0;
        jQuery.each(jQuery('.ant-tabs-tab-inner'),function(){
            array.push(jQuery(this)); 
        });
        detailData && toJS(detailData).map(data => {
            array[i].attr('title',data.hreftitle);
            i++;
        });
        
        if (countDisplayPosition==='2' && countData.length>0) { //countDisplayPosition:统计-显示位置 ['0':顶部显示、'1':顶部简约显示、'2':右上角显示]
            this.showCountDataOnTopRight();
        }
    }

    /* 统计 在右上角显示时，将超出部分以下拉框形式显示 type:'selectedKey'时需重新计算下拉框宽度*/
    showCountDataOnTopRight = () => {
        const { customPageStore } = this.props;
        const { handleShowMoreCountData } = customPageStore;
        const $topCountDataMore = jQuery('#custompage-top-countData-more');
        if ($topCountDataMore.length > 0) {
            setTimeout(function(){  // 增加延迟函数为解决 行点击事件触发右侧iframe展开 导致的页面宽度改变，避免本函数内计算时获取的仍是旧宽度的问题
                // 恢复样式
                jQuery('.wea-new-top .cube-custompage-top-countData').attr('style','');
                jQuery('.wea-new-top .cube-custompage-top-countData-more').attr('style','');
                jQuery('#custompage-top-countData-list').attr('style','');
                $topCountDataMore.show();
                /*  动态计算“统计项”展示的宽度  */
                const containerWidth = jQuery('#custompage-top-countData-more').parents(".wea-new-top").width(); // top宽度
                const containerToLeft = jQuery('#custompage-top-countData-more').parents(".wea-new-top").offset().left; // wea-new-top距左侧的距离
                const topCountMoreToLeft = jQuery('#custompage-top-countData-more').offset().left; // custompage-top-countData-more按钮距左侧的距离
                // 计算 top右侧的快捷搜索按钮宽度和  快捷搜索按钮宽度和 = top宽度 + wea-new-top距左侧的距离 - custompage-top-countData-more按钮距左侧的距离
                const btnsWidth = containerWidth + containerToLeft - topCountMoreToLeft;

                const newTopTitleWidth = jQuery('.coms-mode-viewCustomPage .wea-new-top .ant-col-14 .wea-new-top-title').width(); // top 标题 整体宽度
                let newTopTitleBreadcrumbWidth = jQuery('.coms-mode-viewCustomPage .wea-new-top .wea-new-top-title .wea-new-top-title-breadcrumb').width(); // top 标题文字宽度
                /**
                 * 由于ie浏览器下 span内文字长度会超过span元素的宽度，而获取到的是span的宽度，因此当span内文字过长时，依然存在与右侧“统计项”重叠的问题
                 * 因此需要增加判断，当newTopTitleBreadcrumbWidth快要超过父元素newTopTitleWidth的宽度时，就采用父元素newTopTitleWidth的宽度
                 */
                if (!jQuery.browser.chrome && newTopTitleBreadcrumbWidth+100>newTopTitleWidth) {
                    newTopTitleBreadcrumbWidth = newTopTitleWidth;
                }
                // 计算top左侧标题宽度
                const leftTitleWidth = Math.min(newTopTitleWidth, newTopTitleBreadcrumbWidth);

                // 计算留给'统计'展示的剩余宽度  留给'统计'展示的剩余宽度 = top宽度 - top标题宽度 - 右侧快捷按钮宽度和
                const fixedWidth = Math.min(containerWidth - leftTitleWidth, containerWidth*0.6) - btnsWidth - 60;
                let countDataWidthSum = 0; // 所有“统计项”总宽度
                let topCountDataWidth = 0; // 展示在top中的“统计项”总宽度
                let index = 0; //隐藏的'统计项'数量

                const $topCountDataList = jQuery('.wea-new-top .cube-custompage-top-countData'); // 水平展示'统计'项
                const $topCountDataListMore = jQuery('.wea-new-top .cube-custompage-top-countData-more'); // 下拉展示'统计'项
                // 计算'统计'项的总宽度
                $topCountDataListMore.each(function() {
                    countDataWidthSum += jQuery(this).width();
                });
                if (countDataWidthSum > fixedWidth) { // 判断是否需要显示“显示更多”按钮
                    $topCountDataMore.show(); // 需要显示“显示更多”按钮
                    jQuery('#custompage-top-countData-more .icon-coms').css('visibility','visible');
                    // 当top展示的“统计项”总长度小于可展示位置的宽度，则从左至右将“统计项”显示在top中
                    while (topCountDataWidth + $topCountDataListMore.eq(index).width() + 10 < fixedWidth) {
                        topCountDataWidth += $topCountDataListMore.eq(index).width() + 10;
                        $topCountDataList.eq(index).css('display','inline-block');
                        $topCountDataListMore.eq(index).css('display','none');
                        index++;
                    }
                    // 由于ie与Chrome计算宽度的不同，ie下会出现重叠现象，因此隐藏一个统计项避免重叠
                    if (!jQuery.browser.chrome && index > 0) {
                        index--;
                        topCountDataWidth = topCountDataWidth - $topCountDataListMore.eq(index).width() - 10;
                        $topCountDataList.eq(index).css('display','none');
                        $topCountDataListMore.eq(index).css('display','inline-block');
                    }
                } else {
                    $topCountDataMore.hide(); // 不需要显示“显示更多”按钮
                    $topCountDataList.css('display','inline-block');
                    $topCountDataListMore.css('display','none');
                }

                // 调整下拉列表位置/宽度
                jQuery('#custompage-top-countData-list').css({'width':topCountDataWidth+22, 'right':btnsWidth - 14});
                document.addEventListener('click', () => {
                    handleShowMoreCountData(true);
                });
            },200);
        }
    }

    getTabDatas = () => {
        const { customPageStore } = this.props;
        const { detailData } = customPageStore;
        let buttonArr: any = [];
        detailData && toJS(detailData).map(data => {
            buttonArr.push({
                key: data.detailid,
                title: data.hrefname
            })
        });
        return buttonArr;
    }

    tabChange = v => { 
        const { customPageStore } = this.props;
        let query;
        if(this.props['location']&&this.props['location']['query']){
            query=this.props['location']['query'];
        }
        customPageStore.tabChange(v,query) 
    }

    getComContent = () => {
        const { customPageStore } = this.props;
       
        const {  selectedKey, search, card, } = customPageStore;
        return (
            <Fragment>
                <WeaTab
                    datas={this.getTabDatas()}
                    keyParam="key"  //主键
                    selectedKey={selectedKey}
                    onChange={this.tabChange}
                />
                 <div className="cube-custompage-container" style={{ display: customPageStore.mainFrameRefVisible ? "block" : 'none' }}>
                    <iframe id="cube-custompage-div" src="about:blank" width="100%" height="100%" frameBorder="0" scrolling="auto"></iframe>
                </div>
                {
                    customPageStore.isSearchShow && search.isInit &&
                    <div className="cube-card-list-wrapper" style={{height:`calc( 100% - 48px)`}}>
                        <List Search={search} hideRightmenu={true}/>
                    </div>
                }
                {
                    customPageStore.isCardShow && customPageStore.card.isInit &&
                    <div className="coms-mode-docker coms-mode-card">
                        <InnerTabCard Card={card} Search={search} hideRightmenu={true}/>
                    </div>
                }
                {
                    customPageStore.isShowReply ? (customPageStore.reply.showReply ?
                        <div style={{ paddingTop: 25 }}><ReplySingle reply={customPageStore.reply} /></div>
                        : <WeaAlertPage>
                            <div style={{ color: '#000' }}>{getLabel(387029, "请开启回复评论显示")}</div>
                        </WeaAlertPage>) 
                    : ""
                }
                {
                    customPageStore.isTreeShow &&
                    <Tree
                        Tree={customPageStore.tree}
                        Card={card}
                        Search={search}
                        reply={customPageStore.reply}
                        customPageStore={customPageStore}
                    />
                }
            </Fragment>
        )
    }
    
    quickButtons = () => {
        const { customPageStore, Search } = this.props;
        const { rightMenus, rightMenuHandle, showMoreCountData, isSearchShow } = customPageStore;
        const { countData, countDisplayPosition } = Search;
        const quickRightMenus = rightMenus ? rightMenus.filter(d => d.quickButton) : [];
        let butArrs: any = [];
        let arr:any = [], arrMore:any = [];
        // 自定义页面仅查询列表（即isSearchShow为true）时需要执行判断内容
        if (isSearchShow && countDisplayPosition === '2' && countData.length>0) { //countDisplayPosition:统计-显示位置 ['0':顶部显示、'1':顶部简约显示、'2':右上角显示]
            countData.forEach(item=>{
                arr.push(
                    <div className="cube-custompage-top-countData">
                        <i className={item.icon} />
                        <span className="cube-custompage-top-countData-title">{item.name}:</span>
                        <b>{item.countnum}</b>
                        {item.setdesc&&<WeaHelpfulTip width={"auto"} style={{ paddingLeft:'5px' }} title={item.setdesc} />}
                    </div>
                );
                arrMore.push(
                    <div className="cube-custompage-top-countData-more">
                        <i className={item.icon} />
                        <span className="cube-custompage-top-countData-title">{item.name}:</span>
                        <b>{item.countnum}</b>
                        {item.setdesc&&<WeaHelpfulTip width={"auto"} style={{ paddingLeft:'5px' }} title={item.setdesc} />}
                    </div>
                );
            });
            arr.push(
                <div id="custompage-top-countData-more" onClick={this.countDataClick}>
                    <i className={showMoreCountData?'icon-coms icon-coms-up2':'icon-coms icon-coms-down2'} />
                    <span id="custompage-top-countData-list" className={showMoreCountData?'showMore':''}>{arrMore}</span>
                </div>
            )
            butArrs.push(arr);
        }
        quickRightMenus.forEach(d => (
            butArrs.push(<Button type="primary" onClick={()=>{rightMenuHandle(d.key)}}>{d.content}</Button>)
        ));
        return butArrs;
    }
    countDataClick = (e) => {
        const { customPageStore } = this.props;
        const { showMoreCountData, handleShowMoreCountData } = customPageStore;
        e.nativeEvent.stopImmediatePropagation();
        handleShowMoreCountData(showMoreCountData);
    }

    render() {
        const { customPageStore} = this.props;
        if(customPageStore.windowTitle != ""){
            document.title = customPageStore.windowTitle;
        }
        const { getTitle, loading, rightMenus, rightMenuHandle ,iconInfo,params } = customPageStore;
        let hidetop = params['hidetop'] && params['hidetop'] == 1;
        const topAndCom =  !hidetop ? 
            (<WeaTop
                title={getTitle}
                loading={loading}
                icon={<i className={iconInfo.icon} style={{color:iconInfo.iconColor}} />}
                iconBgcolor={iconInfo.iconBg}
                showDropIcon={true}
                dropMenuDatas={rightMenus}
                onDropMenuClick={rightMenuHandle}
                buttons={this.quickButtons()}
            >
                {this.getComContent()}
            </WeaTop>) : this.getComContent()
        if(customPageStore.isTreeShow) {//树 隐藏自定义页面右键菜单
            return topAndCom
        }else{
            return (
                <WeaRightMenu
                    datas={rightMenus}
                    onClick={rightMenuHandle}
                    collectParams={{
                        "favname": getTitle,
                        "link": '/' + window.location.toString().split('/').slice(3).join('/'),
                        "favouritetype": 5,
                        "importantlevel": 1
                    }}
                >
                    {topAndCom}                   
                </WeaRightMenu>
            )
        }
    }

}
